<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>元素居中的多种方式 | dmf的个人博客</title><meta name="author" content="dmf"><meta name="copyright" content="dmf"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="描述">
<meta property="og:type" content="article">
<meta property="og:title" content="元素居中的多种方式">
<meta property="og:url" content="https://gitee.com/dmf-c/blog/2021/03/20/css_file/ElementCentered/index.html">
<meta property="og:site_name" content="dmf的个人博客">
<meta property="og:description" content="描述">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img1.baidu.com/it/u=1828439677,2166285235&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=300">
<meta property="article:published_time" content="2021-03-19T16:00:00.000Z">
<meta property="article:modified_time" content="2022-10-12T07:13:19.243Z">
<meta property="article:author" content="dmf">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img1.baidu.com/it/u=1828439677,2166285235&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=300"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://gitee.com/dmf-c/blog/2021/03/20/css_file/ElementCentered/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '元素居中的多种方式',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-10-12 15:13:19'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">27</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/blog/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/blog/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">dmf的个人博客</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/blog/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/blog/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">元素居中的多种方式</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="fa-fw post-meta-icon far fa-calendar-alt"></i><span class="post-meta-label">发表于</span><time datetime="2021-03-19T16:00:00.000Z" title="发表于 2021-03-20 00:00:00">2021-03-20</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/css/">css</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="元素居中的多种方式"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p><a target="_blank" rel="noopener" href="https://imgse.com/i/xUJIb9"><img src="https://s1.ax1x.com/2022/10/12/xUJIb9.png" alt="xUJIb9.png"></a></p>
<h2 id="水平居中"><a href="#水平居中" class="headerlink" title="水平居中"></a>水平居中</h2><h3 id="行内元素水平居中"><a href="#行内元素水平居中" class="headerlink" title="行内元素水平居中"></a>行内元素水平居中</h3><p><strong>利用 text-align: center 可以实现在块级元素内部的行内元素水平居中。</strong>此方法对inline、inline-block、inline-table和inline-flex元素水平居中都有效。</p>
<pre><code>.parent&#123;//在父容器设置
     text-align:center;
 &#125;
</code></pre>
<p>此外，如果块级元素内部包着也是一个块级元素，<strong>我们可以先将其由块级元素改变为行内块元素，再通过设置行内块元素居中以达到水平居中。</strong></p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
&lt;div class=&quot;child&quot;&gt;Demo&lt;/div&gt;
&lt;/div&gt;
&lt;style&gt;
.parent&#123;
    text-align:center;  
&#125;
.child &#123;
    display: inline-block;
&#125;
&lt;/style&gt;
</code></pre>
<h3 id="块级元素的水平居中"><a href="#块级元素的水平居中" class="headerlink" title="块级元素的水平居中"></a>块级元素的水平居中</h3><p><strong>①将该块级元素左右外边距margin-left和margin-right设置为auto</strong></p>
<pre><code>.child&#123;
    width: 100px;//确保该块级元素定宽
    margin:0 auto;
&#125;
</code></pre>
<p><strong>②使用table+margin</strong></p>
<p><strong>先将子元素设置为块级表格来显示（类似），再将其设置水平居中</strong></p>
<p><strong>display:table在表现上类似block元素，但是宽度为内容宽。</strong></p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
&lt;div class=&quot;child&quot;&gt;Demo&lt;/div&gt;
&lt;/div&gt;
&lt;style&gt;
.child &#123;
    display: table;
    margin: 0 auto;
&#125;
&lt;/style&gt;
</code></pre>
<p><strong>③使用absolute+transform</strong></p>
<p><strong>先将父元素设置为相对定位，再将子元素设置为绝对定位，向右移动子元素，移动距离为父容器的一半，最后通过向左移动子元素的一半宽度以达到水平居中。</strong></p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
&lt;div class=&quot;child&quot;&gt;Demo&lt;/div&gt;
&lt;/div&gt;
&lt;style&gt;
.child &#123;
    position:absolute;
    left:50%;
    transform:translateX(-50%);
&#125;
.parent &#123;
    position:relative;
&#125;
&lt;/style&gt;
</code></pre>
<p><strong>不过transform属于css3内容，兼容性存在一定问题，有些版本浏览器需要添加一些前缀。</strong></p>
<p><strong>④使用flex+justify-content</strong></p>
<p><strong>通过CSS3中的布局利器flex中的justify-content属性来达到水平居中。</strong></p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
&lt;div class=&quot;child&quot;&gt;Demo&lt;/div&gt;
&lt;/div&gt;
&lt;style&gt;
.parent &#123;
    display: flex;
    justify-content:center;
&#125;
&lt;/style&gt;
</code></pre>
<p><strong>⑤使用flex+margin</strong></p>
<p><strong>通过flex将父容器设置为为Flex布局，再设置子元素居中。</strong></p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
&lt;div class=&quot;child&quot;&gt;Demo&lt;/div&gt;
&lt;/div&gt;
&lt;style&gt;
.parent &#123;
    display: flex;
&#125;
.child &#123;
    margin:0 auto;
&#125;
&lt;/style&gt;
</code></pre>
<h3 id="多块级元素水平居中"><a href="#多块级元素水平居中" class="headerlink" title="多块级元素水平居中"></a>多块级元素水平居中</h3><p><a target="_blank" rel="noopener" href="https://imgse.com/i/xUYRII"><img src="https://s1.ax1x.com/2022/10/12/xUYRII.png" alt="xUYRII.png"></a></p>
<p><strong>①利用flex布局</strong></p>
<p><strong>利用弹性布局(flex)，实现水平居中，其中justify-content 用于设置弹性盒子元素在主轴（默认横轴）方向上的对齐方式，</strong>本例中设置子元素水平居中显示。</p>
<pre><code>#container &#123;
    display: flex;
    justify-content: center;
&#125;
</code></pre>
<p><strong>②利用inline-block</strong></p>
<p><strong>将要水平排列的块状元素设为display:inline-block，然后在父级元素上设置text-align:center，达到与上面的行内元素的水平居中一样的效果。</strong></p>
<pre><code>.container &#123;
text-align: center;
&#125;
.inline-block &#123;
display: inline-block;
&#125;
</code></pre>
<h3 id="浮动元素水平居中"><a href="#浮动元素水平居中" class="headerlink" title="浮动元素水平居中"></a>浮动元素水平居中</h3><ul>
<li><p>对于定宽的浮动元素，通过子元素设置relative + 负margin</p>
</li>
<li><p>对于不定宽的浮动元素，父子容器都用相对定位</p>
</li>
<li><p>通用方法(不管是定宽还是不定宽)：flex布局</p>
</li>
</ul>
<p><strong>①定宽的非浮动元素</strong></p>
<p><strong>通过子元素设置relative + 负margin,原理见下图：</strong></p>
<p><a target="_blank" rel="noopener" href="https://imgse.com/i/xUYhJP"><img src="https://s1.ax1x.com/2022/10/12/xUYhJP.png" alt="xUYhJP.png"></a></p>
<p><strong>注意：样式设置在浮动元素本身</strong></p>
<pre><code>.child &#123;
position:relative;
left:50%;
margin-left:-250px;
&#125;
&lt;div class=&quot;parent&quot;&gt;
&lt;span class=&quot;child&quot; style=&quot;float: left;width: 500px;&quot;&gt;我是要居中的浮动元素&lt;/span&gt;
&lt;/div&gt;
</code></pre>
<p><strong>②不定宽的浮动元素</strong></p>
<p>通过父子容器都相对定位，偏移位移见下图：</p>
<p><a target="_blank" rel="noopener" href="https://imgse.com/i/xUt9L4"><img src="https://s1.ax1x.com/2022/10/12/xUt9L4.png" alt="xUt9L4.png"></a></p>
<p><strong>注意：要清除浮动，给外部元素加上float。这里的父元素就是外部元素</strong></p>
<pre><code>&lt;div class=&quot;box&quot;&gt;
    &lt;p&gt;我是浮动的&lt;/p&gt;
    &lt;p&gt;我也是居中的&lt;/p&gt;
&lt;/div&gt;
.box&#123;
    float:left;
    position:relative;
    left:50%;
&#125;
p&#123;
    float:left;
    position:relative;
    right:50%;
&#125;
</code></pre>
<p><strong>③通用办法flex布局(不管是定宽还是不定宽)</strong></p>
<p><strong>利用弹性布局(flex)的justify-content属性，实现水平居中。</strong></p>
<pre><code>.parent &#123;
    display:flex;
    justify-content:center;
&#125;
.chlid&#123;
    float: left;
    width: 200px;//有无宽度不影响居中
&#125;
&lt;div class=&quot;parent&quot;&gt;
&lt;span class=&quot;chlid&quot;&gt;我是要居中的浮动元素&lt;/span&gt;
&lt;/div&gt;
</code></pre>
<h3 id="绝对定位元素水平居中"><a href="#绝对定位元素水平居中" class="headerlink" title="绝对定位元素水平居中"></a>绝对定位元素水平居中</h3><p>这种方式非常独特，<strong>通过子元素绝对定位，外加margin: 0 auto来实现。</strong></p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
    &lt;div class=&quot;child&quot;&gt;让绝对定位的元素水平居中对齐。&lt;/div&gt;
&lt;/div&gt;
.parent&#123;
        position:relative;
    &#125;
.child&#123;
        position: absolute; /*绝对定位*/
        width: 200px;
        height:100px;
        background: yellow;
        margin: 0 auto; /*水平居中*/
        left: 0; /*此处不能省略，且为0*/
        right: 0;/*此处不能省略，且为0*/
    &#125;
</code></pre>
<h2 id="垂直居中"><a href="#垂直居中" class="headerlink" title="垂直居中"></a>垂直居中</h2><h3 id="单行内联元素垂直居中"><a href="#单行内联元素垂直居中" class="headerlink" title="单行内联元素垂直居中"></a>单行内联元素垂直居中</h3><pre><code>&lt;div id=&quot;box&quot;&gt;
    &lt;span&gt;单行内联元素垂直居中。&lt;/span&gt;。
&lt;/div&gt;
&lt;style&gt;
#box &#123;
    height: 120px;
    line-height: 120px;
    border: 2px dashed #f69c55;
    &#125;
&lt;/style&gt;
</code></pre>
<h3 id="多行内联元素垂直居中"><a href="#多行内联元素垂直居中" class="headerlink" title="多行内联元素垂直居中"></a>多行内联元素垂直居中</h3><p><strong>①利用flex布局（flex）</strong></p>
<p><strong>利用flex布局实现垂直居中，其中flex-direction: column定义主轴方向为纵向。</strong>这种方式在较老的浏览器存在兼容性问题。</p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
    &lt;p&gt;Dance like nobody is watching, code like everybody is.    
    Dance like nobody is watching, code like everybody is.    
    Dance like nobody is watching, code like everybody is.&lt;/p&gt;
&lt;/div&gt;
&lt;style&gt;
    .parent &#123; 
        height: 140px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        border: 2px dashed #f69c55;
    &#125;
&lt;/style&gt;
</code></pre>
<p><a target="_blank" rel="noopener" href="https://imgse.com/i/xUtFoR"><img src="https://s1.ax1x.com/2022/10/12/xUtFoR.png" alt="xUtFoR.png"></a></p>
<p><strong>②利用表布局（table）</strong></p>
<p><strong>利用表布局的vertical-align: middle可以实现子元素的垂直居中</strong></p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
    &lt;p class=&quot;child&quot;&gt;The more technology you learn, the more you realize how little you know.
    The more technology you learn, the more you realize how little you know.
    The more technology you learn, the more you realize how little you know.&lt;/p&gt;
&lt;/div&gt;
&lt;style&gt;
    .parent &#123;
        display: table;
        height: 140px;
        border: 2px dashed #f69c55;
    &#125;
    .child &#123;
        display: table-cell;
        vertical-align: middle;
    &#125;
&lt;/style&gt;
</code></pre>
<h3 id="块级元素垂直居中"><a href="#块级元素垂直居中" class="headerlink" title="块级元素垂直居中"></a>块级元素垂直居中</h3><p><strong>①使用absolute+负margin(已知高度宽度)</strong></p>
<p><strong>通过绝对定位元素距离顶部50%，并设置margin-top向上偏移元素高度的一半，就可以实现了。</strong></p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
    &lt;div class=&quot;child&quot;&gt;固定高度的块级元素垂直居中。&lt;/div&gt;
&lt;/div&gt;
.parent &#123;
position: relative;
&#125;
.child &#123;
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px;
&#125;
</code></pre>
<p><strong>②使用absolute+transform</strong></p>
<p><strong>当垂直居中的元素的高度和宽度未知时，可以借助CSS3中的transform属性向Y轴反向偏移50%的方法实现垂直居中。</strong>但是部分浏览器存在兼容性的问题。</p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
    &lt;div class=&quot;child&quot;&gt;未知高度的块级元素垂直居中。&lt;/div&gt;
&lt;/div&gt;
.parent &#123;
position: relative;
&#125;
.child &#123;
position: absolute;
top: 50%;
transform: translateY(-50%);
&#125;
</code></pre>
<p><strong>③使用flex+align-items</strong></p>
<p><strong>通过设置flex布局中的属性align-items，使子元素垂直居中。</strong></p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
    &lt;div class=&quot;child&quot;&gt;未知高度的块级元素垂直居中。&lt;/div&gt;
&lt;/div&gt;
.parent &#123;
    display:flex;
    align-items:center;
&#125;
</code></pre>
<p><strong>④使用table-cell+vertical-align</strong></p>
<p><strong>通过将父元素转化为一个表格单元格显示（类似 <td> 和 <th>），再通过设置 vertical-align属性，使表格单元格内容垂直居中。</strong></p>
<pre><code>&lt;div class=&quot;parent&quot;&gt;
&lt;div class=&quot;child&quot;&gt;Demo&lt;/div&gt;
&lt;/div&gt;
&lt;style&gt;
.parent &#123;
    display: table-cell;
    vertical-align: middle;
&#125;
&lt;/style&gt;
</code></pre>
<h2 id="水平垂直居中"><a href="#水平垂直居中" class="headerlink" title="水平垂直居中"></a>水平垂直居中</h2><h3 id="绝对定位与负边距实现（已知高度宽度）"><a href="#绝对定位与负边距实现（已知高度宽度）" class="headerlink" title="绝对定位与负边距实现（已知高度宽度）"></a>绝对定位与负边距实现（已知高度宽度）</h3><p><strong>这种方式需要知道被垂直居中元素的高和宽，才能计算出margin值，兼容所有浏览器。</strong></p>
<pre><code>// css部分
#container &#123;
    position: relative;
    &#125;
#center &#123;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -50px 0 0 -50px;
    &#125;

// html部分(这部分不做变化,下面例子直接共用)
&lt;body&gt;
&lt;div id=&#39;container&#39;&gt;
    &lt;div id=&#39;center&#39; style=&quot;width: 100px;height: 100px;background-color: #666&quot;&gt;center&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
</code></pre>
<h3 id="绝对定位与margin-auto（已知高度宽度）"><a href="#绝对定位与margin-auto（已知高度宽度）" class="headerlink" title="绝对定位与margin:auto（已知高度宽度）"></a>绝对定位与margin:auto（已知高度宽度）</h3><p><strong>这种方式无需知道被垂直居中元素的高和宽，但不能兼容低版本的IE浏览器。</strong></p>
<pre><code>#container &#123;
    position: relative;
    height:100px;//必须有个高度
    &#125;
#center &#123;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;//注意此处的写法
    &#125;
</code></pre>
<h3 id="绝对定位-CSS3-未知元素的高宽"><a href="#绝对定位-CSS3-未知元素的高宽" class="headerlink" title="绝对定位+CSS3(未知元素的高宽)"></a>绝对定位+CSS3(未知元素的高宽)</h3><p><strong>利用Css3的transform，可以轻松的在未知元素的高宽的情况下实现元素的垂直居中。</strong><br>CSS3的transform固然好用，但在项目的实际运用中必须考虑兼容问题，大量的hack代码可能会导致得不偿失。</p>
<pre><code>#container &#123;
    position: relative;
    &#125;
#center &#123;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    &#125;
</code></pre>
<h3 id="flex布局"><a href="#flex布局" class="headerlink" title="flex布局"></a>flex布局</h3><p><strong>利用flex布局，其中justify-content 用于设置或检索弹性盒子元素在主轴（横轴）方向上的对齐方式；而align-items属性定义flex子项在flex容器的当前行的侧轴（纵轴）方向上的对齐方式。不能兼容低版本的IE浏览器。</strong></p>
<pre><code>#container &#123;//直接在父容器设置即可
    height: 100vh;//必须有高度
    display: flex;
    justify-content: center;
    align-items: center;
    &#125;
</code></pre>
<h3 id="flex-x2F-grid与margin-auto-最简单写法"><a href="#flex-x2F-grid与margin-auto-最简单写法" class="headerlink" title="flex&#x2F;grid与margin:auto(最简单写法)"></a>flex&#x2F;grid与margin:auto(最简单写法)</h3><p><strong>容器元素设为 flex 布局或是grid布局，子元素只要写 margin: auto 即可,不能兼容低版本的IE浏览器。</strong></p>
<pre><code>#container &#123;
    height: 100vh;//必须有高度
    display: grid;
    &#125;
#center &#123;
    margin: auto;
    &#125;
</code></pre>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://gitee.com/dmf-c/blog">dmf</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://gitee.com/dmf-c/blog/2021/03/20/css_file/ElementCentered/">https://gitee.com/dmf-c/blog/2021/03/20/css_file/ElementCentered/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://gitee.com/dmf-c/blog" target="_blank">dmf的个人博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2021/04/02/css_file/BFC/"><img class="prev-cover" src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">BFC(块级格式化上下文)</div></div></a></div><div class="next-post pull-right"><a href="/blog/2021/03/05/css_file/flex/"><img class="next-cover" src="https://img1.baidu.com/it/u=3691791879,443411760&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=500&amp;h=889" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">flex属性参数</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">dmf</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">27</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">业精于勤，荒于嬉。</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B0%B4%E5%B9%B3%E5%B1%85%E4%B8%AD"><span class="toc-number">1.</span> <span class="toc-text">水平居中</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A1%8C%E5%86%85%E5%85%83%E7%B4%A0%E6%B0%B4%E5%B9%B3%E5%B1%85%E4%B8%AD"><span class="toc-number">1.1.</span> <span class="toc-text">行内元素水平居中</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9D%97%E7%BA%A7%E5%85%83%E7%B4%A0%E7%9A%84%E6%B0%B4%E5%B9%B3%E5%B1%85%E4%B8%AD"><span class="toc-number">1.2.</span> <span class="toc-text">块级元素的水平居中</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A4%9A%E5%9D%97%E7%BA%A7%E5%85%83%E7%B4%A0%E6%B0%B4%E5%B9%B3%E5%B1%85%E4%B8%AD"><span class="toc-number">1.3.</span> <span class="toc-text">多块级元素水平居中</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%AE%E5%8A%A8%E5%85%83%E7%B4%A0%E6%B0%B4%E5%B9%B3%E5%B1%85%E4%B8%AD"><span class="toc-number">1.4.</span> <span class="toc-text">浮动元素水平居中</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%9D%E5%AF%B9%E5%AE%9A%E4%BD%8D%E5%85%83%E7%B4%A0%E6%B0%B4%E5%B9%B3%E5%B1%85%E4%B8%AD"><span class="toc-number">1.5.</span> <span class="toc-text">绝对定位元素水平居中</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD"><span class="toc-number">2.</span> <span class="toc-text">垂直居中</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8D%95%E8%A1%8C%E5%86%85%E8%81%94%E5%85%83%E7%B4%A0%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD"><span class="toc-number">2.1.</span> <span class="toc-text">单行内联元素垂直居中</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A4%9A%E8%A1%8C%E5%86%85%E8%81%94%E5%85%83%E7%B4%A0%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD"><span class="toc-number">2.2.</span> <span class="toc-text">多行内联元素垂直居中</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9D%97%E7%BA%A7%E5%85%83%E7%B4%A0%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD"><span class="toc-number">2.3.</span> <span class="toc-text">块级元素垂直居中</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B0%B4%E5%B9%B3%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD"><span class="toc-number">3.</span> <span class="toc-text">水平垂直居中</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%9D%E5%AF%B9%E5%AE%9A%E4%BD%8D%E4%B8%8E%E8%B4%9F%E8%BE%B9%E8%B7%9D%E5%AE%9E%E7%8E%B0%EF%BC%88%E5%B7%B2%E7%9F%A5%E9%AB%98%E5%BA%A6%E5%AE%BD%E5%BA%A6%EF%BC%89"><span class="toc-number">3.1.</span> <span class="toc-text">绝对定位与负边距实现（已知高度宽度）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%9D%E5%AF%B9%E5%AE%9A%E4%BD%8D%E4%B8%8Emargin-auto%EF%BC%88%E5%B7%B2%E7%9F%A5%E9%AB%98%E5%BA%A6%E5%AE%BD%E5%BA%A6%EF%BC%89"><span class="toc-number">3.2.</span> <span class="toc-text">绝对定位与margin:auto（已知高度宽度）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%9D%E5%AF%B9%E5%AE%9A%E4%BD%8D-CSS3-%E6%9C%AA%E7%9F%A5%E5%85%83%E7%B4%A0%E7%9A%84%E9%AB%98%E5%AE%BD"><span class="toc-number">3.3.</span> <span class="toc-text">绝对定位+CSS3(未知元素的高宽)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#flex%E5%B8%83%E5%B1%80"><span class="toc-number">3.4.</span> <span class="toc-text">flex布局</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#flex-x2F-grid%E4%B8%8Emargin-auto-%E6%9C%80%E7%AE%80%E5%8D%95%E5%86%99%E6%B3%95"><span class="toc-number">3.5.</span> <span class="toc-text">flex&#x2F;grid与margin:auto(最简单写法)</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/01/08/vue_file/vuenote/" title="vue3入门笔记"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="vue3入门笔记"/></a><div class="content"><a class="title" href="/blog/2023/01/08/vue_file/vuenote/" title="vue3入门笔记">vue3入门笔记</a><time datetime="2023-01-07T16:00:00.000Z" title="发表于 2023-01-08 00:00:00">2023-01-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/02/20/vue_file/comm/" title="vue组件间通信六种方式"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="vue组件间通信六种方式"/></a><div class="content"><a class="title" href="/blog/2022/02/20/vue_file/comm/" title="vue组件间通信六种方式">vue组件间通信六种方式</a><time datetime="2022-02-19T16:00:00.000Z" title="发表于 2022-02-20 00:00:00">2022-02-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/02/05/wxEcharts/" title="微信小程序使用 echarts"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="微信小程序使用 echarts"/></a><div class="content"><a class="title" href="/blog/2022/02/05/wxEcharts/" title="微信小程序使用 echarts">微信小程序使用 echarts</a><time datetime="2022-02-04T16:00:00.000Z" title="发表于 2022-02-05 00:00:00">2022-02-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/01/30/vue_file/vue_router/" title="vue-router学习"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="vue-router学习"/></a><div class="content"><a class="title" href="/blog/2022/01/30/vue_file/vue_router/" title="vue-router学习">vue-router学习</a><time datetime="2022-01-29T16:00:00.000Z" title="发表于 2022-01-30 00:00:00">2022-01-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/01/16/vue_file/vuex/" title="Vuex使用方法"><img src="https://img1.baidu.com/it/u=1828439677,2166285235&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=400&amp;h=300" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Vuex使用方法"/></a><div class="content"><a class="title" href="/blog/2022/01/16/vue_file/vuex/" title="Vuex使用方法">Vuex使用方法</a><time datetime="2022-01-15T16:00:00.000Z" title="发表于 2022-01-16 00:00:00">2022-01-16</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By dmf</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>